//
//  TouXiangController.m
//  FangYunERP
//
//  Created by MichaelLi on 2017/12/11.
//  Copyright © 2017年 YuHuaMac. All rights reserved.
//

#import "SettingTabVC.h"
#import "TouXiangCell.h"
#import "CustomePickerImageVC.h"
#import "TYAlertController.h"
#import "UIView+TYAlertView.h"
#import "SettingModelView.h"
#import "TZImagePickerController.h"
#import "CustomePickerImageVC.h"
#import "ChangePSWView.h"
#import "MainNavC.h"
#import "ForgotPSWVC.h"
#import "HomeTabVC.h"
@interface SettingTabVC ()<UINavigationControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UINavigationBarDelegate,TZImagePickerControllerDelegate,UITextViewDelegate>
@property(nonatomic,strong) NSArray *dataArray;
@property(nonatomic,strong) UIImage *image;
@property(nonatomic,strong) NSString *imageString;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) UITextView *textView;
@property(nonatomic,strong) NSString *nickNamed;
@property(nonatomic,strong) NSString *phone;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) ChangePSWView *changePWSView;
@property(nonatomic,strong) HomeTabVC *homeTabVC;
@property(nonatomic,assign) NSInteger row;
@end
static NSString *identifier = @"cell";
static NSString *identifierIcon = @"cellIcon";
@implementation SettingTabVC
/**
 http://www.qichangkeji.vip/qckjgzh/user/updateHeadImg?userId=53&guId=10294&headImg=123123123
 */
-(NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置";
    self.manager = [AFHTTPSessionManager manager];
    self.homeTabVC = [[HomeTabVC alloc]init];
    self.nickNamed = [UserDefaultsHelper readNickName];
    self.phone = [UserDefaultsHelper readIphone];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:@"TouXiangCell" bundle:nil] forCellReuseIdentifier:identifierIcon];
     UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(kUIScreen.size.width*0.05, kUIScreen.size.height*0.6, kUIScreen.size.width*0.9, 44)];
    [button setTitle:@"退出登录" forState:UIControlStateNormal];
//    [button setBackgroundColor:[UIColor colorWithRed:14/255.0 green:107/255.0 blue:255/255.0 alpha:1] ];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    button.layer.cornerRadius = 3;
    button.layer.borderColor  = kOrangeBg.CGColor;
    button.layer.borderWidth  = 1;
    [button setTitleColor:kOrangeBg forState:UIControlStateNormal];
    [button setTitleColor:kBg forState:UIControlStateHighlighted];
    [self.tableView addSubview:button];
    [button addTarget: self action:@selector(logOut) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkTokenSetting:) name:@"checkTokenSetting" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkTokenError:) name:@"checkTokenError" object:nil];
}

-(void)logOut
{
    [UserDefaultsHelper saveAutoLogIn:nil value:nil];
    [UserDefaultsHelper saveIphone:@"" value:@""];
    [UserDefaultsHelper saveHeadimg:@"" value:@""];
    [UserDefaultsHelper saveNickName:@"" value:@""];
    [self.tableView reloadData];
    NSNotification *notification = [NSNotification notificationWithName:@"logInOut" object:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notification];
    [LogOutAccount presentOutAccount];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)reloadInternet
{
    [self.tableView reloadData];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if (section == 0) {
//        return 4;
//    }else {
        return 5;
//    }

    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.section == 0) {
        if (indexPath.row == 0) {//头像
            TouXiangCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierIcon forIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.headImg = [UserDefaultsHelper readHeadimg];
            return cell;
        } else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if(!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            }
            cell.textLabel.font = [UIFont systemFontOfSize:16];
            cell.textLabel.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
            if (indexPath.row == 1) {
                cell.textLabel.text = @"昵称";
                XLog(@"[UserDefaultsHelper readNickName]:%@",[UserDefaultsHelper readNickName]);
                cell.detailTextLabel.text = [UserDefaultsHelper readNickName];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }else if (indexPath.row == 2) {
                cell.textLabel.text = @"账号";
                cell.detailTextLabel.text = [UserDefaultsHelper readIphone];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }else if (indexPath.row == 3) {
                cell.textLabel.text = @"密码修改";
                cell.detailTextLabel.text = @"修改";
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }else {
                cell.textLabel.text = @"版本信息";
                cell.detailTextLabel.text = [NSString stringWithFormat:@"v%@",[self getAPPInfo]];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
            return cell;
        }
}
//获取当前版本
-(NSString *)getAPPInfo{
    NSDictionary *infoDictionary = [[NSBundle mainBundle]infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height;
//    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            height = 80;
        }else {
            height = 50;
        }
//    }else {
//            height = 50;
//    }
    return height;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.row = indexPath.row;
    if (indexPath.row !=2 &&indexPath.row !=4) {
        if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
            [LogOutAccount presentOutAccount];
            [UIAlertViewWarningAccount showWarningAccount];
        }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
            [LogOutAccount presentOutAccount];
        }else {
            self.dict = @{
                          @"userId":[UserDefaultsHelper readUid],
                          @"token":[UserDefaultsHelper readToken],
                          };
            [CustomeManager POSTCheckTokenWithURLIndex:8 parameters:self.dict success:^(NSDictionary *dict) {
            } failure:^(NSError *error) {
                
            }];
        }
    }
}
#pragma mark-代理:token验证后---更改昵称
-(void)checkTokenSetting:(NSNotification *)info
{
    if (self.row == 0) {
        [self sheetControler];
    }else if (self.row == 1) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        SettingModelView *settingModelView = [SettingModelView createViewFromNib];
        [settingModelView.senderBtn setTitle:@"确定" forState:UIControlStateNormal];
        settingModelView.inputTF.text = cell.detailTextLabel.text;
        settingModelView.changeMingZi = YES;
        [settingModelView showInController:self preferredStyle:TYAlertControllerStyleActionSheet backgoundTapDismissEnable:YES];
        TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:settingModelView preferredStyle:TYAlertControllerStyleActionSheet];
        alertController.backgoundTapDismissEnable = YES;
        [self presentViewController:alertController animated:YES completion:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [settingModelView.inputTF becomeFirstResponder];
        });
        settingModelView.returnValueBlock = ^(NSString *nickName) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
            //XLog(@"self.nickname:%@",self.nickname);
            cell.detailTextLabel.text = nickName;
            self.nickNamed = nickName;
            self.dict = @{
                          @"nickName": nickName,
                          @"uid":[UserDefaultsHelper readUid],
                          @"token":[UserDefaultsHelper readToken]
                          };
            XLog(@"dict:%@",self.dict);
            self.urlString = [NSString stringWithFormat:@"%@/user/updateNickname",kUrl];
            [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
            [WSProgressHUD show];
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                XLog(@"responseObject:%@",responseObject);
                //            NSString *message = [responseObject objectForKey:@"message"];
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"昵称更改成功"];
                [UserDefaultsHelper saveNickName:@"" value:nickName];
                XLog(@"readNickName:%@",[UserDefaultsHelper readNickName]);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                XLog(@"error:%@",error);
                [WSProgressHUD dismiss];
            }];
        };
       
    }else if (self.row == 3) {
        ForgotPSWVC *vc = [[ForgotPSWVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)checkTokenError:(NSNotification *)info
{
//    [UIAlertViewWarningAccount showWarningAccount];
//    [LogOutAccount presentOutAccount];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)sheetControler
{
    //打开照相机和图片
    UIAlertController *sheetControler = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    CustomePickerImageVC *picker = [[CustomePickerImageVC alloc]init];
    picker.edgesForExtendedLayout =  UIRectEdgeNone;
    picker.automaticallyAdjustsScrollViewInsets = NO;
    picker.allowsEditing = YES;
    picker.delegate = self;
    sheetControler.popoverPresentationController.sourceView = self.view;
    sheetControler.popoverPresentationController.sourceRect = self.view.frame;
    [self pushTZImagePickerController];
    [self presentViewController:sheetControler animated:YES completion:nil] ;
}
- (void)pushTZImagePickerController {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    TouXiangCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlString = @"http://www.qichangkeji.vip/upload/upload?savePath=img";
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];

    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];

    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.allowTakePicture = YES;

    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    imagePickerVc.showSelectedIndex = YES;
    
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        XLog(@"photos:%@",photos);
        UIImage *image = photos[0];
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        cell.icon.image = image;
        //选择回调
        [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            //
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
            //二进制文件，接口key值，文件路径，图片格式
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSString *stringImg = [responseObject mj_JSONString];
            NSDictionary *dict = [stringImg mj_JSONObject];
            XLog(@"stringImg:%@",stringImg);
            self.imageString = [dict objectForKey:@"path"];
            [self updateHeadImageData];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //XLog(@"error:%@",error);
        }];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark-上传头像
-(void)updateHeadImageData
{
    self.urlString = [NSString stringWithFormat:@"%@/user/changeHeadImg",kUrl];
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"headImg":self.imageString,
                  @"token":[UserDefaultsHelper readToken]
                  };
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /**
         date =     {
         createtime = "<null>";
         headimg = "http://www.qichangkeji.vip/upload/img/b8318ddc-8032-4bcd-a2f8-9294e1892fcb.png";
         id = 12;
         nickname = "\U5566\U5566\U5566";
         password = "<null>";
         phone = 17621764088;
         type = 1;
         };
         message = "\U6210\U529f";
         status = 200;
         }
         */
        XLog(@"responseObject:%@",responseObject);
//        NSString *message = [responseObject objectForKey:@"message"];
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"头像更改成功"];
        [UserDefaultsHelper saveHeadimg:@"" value:self.imageString];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    
    // 提前定位
    __weak typeof(self) weakSelf = self;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerVc = [[UIImagePickerController alloc] init];
        imagePickerVc.delegate = self;
        imagePickerVc.sourceType = sourceType;
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    } else {
        //        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    [tzImagePickerVc showProgressHUD];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    TouXiangCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    cell.icon.image = image;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlString = @"http://www.qichangkeji.vip/upload/upload?savePath=img";
    //选择回调
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        //二进制文件，接口key值，文件路径，图片格式
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSString *stringImg = [responseObject mj_JSONString];
        NSDictionary *dict = [stringImg mj_JSONObject];
        XLog(@"stringImg:%@",stringImg);
        self.imageString = [dict objectForKey:@"path"];
        [self updateHeadImageData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XLog(@"error:%@",error);
    }];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
@end
